package com.qf.blog.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.blog.core.utils.PasswordUtils;
import com.qf.blog.core.utils.UUIDUtils;
import com.qf.blog.web.entity.UserEntity;
import com.qf.blog.web.mapper.UserMapper;
import com.qf.blog.web.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {

    @Override
    public void register(UserEntity userEntity)  {

        // 2.密码加密
        userEntity.setPassword(PasswordUtils.hashPw(userEntity.getPassword()));

        // 3.设置用户的状态
        userEntity.setStatus(1); // 未激活
        userEntity.setCreateTime(new Date());
        userEntity.setActivationCode(UUIDUtils.getId()); // 激活码
        userEntity.setType(0);

        // 4.入库
        int save = baseMapper.insert(userEntity);
    }

    @Override
    public UserEntity byActivationCode(String activationCode)  {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("activation_code",activationCode);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public UserEntity login(String username, String password)  {

        // 1.根据用户用户名查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        UserEntity userEntity = baseMapper.selectOne(queryWrapper);

        if (userEntity == null) {
            return null; // 用户名不存在
        }

        // 2、密码的比对
        if (!PasswordUtils.check(password, userEntity.getPassword())) {
            return null;
        }

        return userEntity;
    }

    @Override
    public void updateHeaderUrl(Integer id, String filePath) {
        baseMapper.updateHeaderUrl(id, filePath);
    }
}
